package com.xmb.wcapi.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmb.wcapi.constant.RandomValidateCode;
import com.xmb.wcapi.shiro.LoginType;
import com.xmb.wcapi.shiro.UserToken;

@Controller
public class LoginController {
	// 刷新验证码
	@RequestMapping("/reFreshRandomCode")
	public void getImage(HttpServletRequest req, HttpServletResponse resp) {
		resp.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
		resp.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expire", 0);
		new RandomValidateCode().getRandcode(req, resp);
	}
	
	@RequestMapping("/")
	public String index(Model model) {
		Subject subject = SecurityUtils.getSubject();
		if(subject.isAuthenticated()){
        	//判断当前用户是否登录 
            return "redirect:/index";
        }else if (subject.isRemembered()){
        	//判断当前用户是否有使用rememberMe 
        	return "redirect:/index";
        }
		return "login/login";
	}
	
	@PostMapping("/login")
	public String login(HttpSession session,@RequestParam("username") String name
			, @RequestParam("password") String password
			, @RequestParam("code") String randomCode
			, @RequestParam(value = "rememberMe", required = false) boolean rememberMe,Model model) {
		
		Object random = session.getAttribute(RandomValidateCode.RANDOMCODEKEY);
		if(StringUtils.isEmpty(randomCode) || random == null || !random.toString().equalsIgnoreCase(randomCode)) {
			model.addAttribute("message", "验证码错误");
			return "login/login";
		}
		session.removeAttribute(RandomValidateCode.RANDOMCODEKEY);
		// 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        //UsernamePasswordToken token = new UsernamePasswordToken(name, password, rememberMe);
        UserToken token = new UserToken(name, password, rememberMe, LoginType.NORMAL.getDesc());
        // 执行认证登陆
        try{
            subject.login(token); //login()方法会调用 Realm类中执行认证逻辑的方法，并将这个参数传递给doGetAuthenticationInfo()方法
        }catch (UnknownAccountException e) { //抛出这个异常说明用户不存在
        	model.addAttribute("message", "用户名或密码错误");
			return "login/login";
        }catch (IncorrectCredentialsException e) { //抛出这个异常说明密码错误
        	model.addAttribute("message", "用户名或密码错误");
			return "login/login";
        }catch (DisabledAccountException e) {
        	model.addAttribute("message", "账号已被禁用");
			return "login/login";
		}catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("message", "系统异常");
			return "login/login";
		}
		return "redirect:/index";
	}
	
	@RequestMapping("/loginOut")
	public String login() {
		SecurityUtils.getSubject().logout();
		return "login/login";
	}
}
